package com.pet.interceptor;

import com.alibaba.fastjson.JSON;
import com.pet.pojo.Result;
import com.pet.util.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;


import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器~");
        //获取客户端携带过来的token
        String token = request.getHeader("token");

        //判断token是否为空 - 如果有空,没有登录
        if("null".equals(token)){
            //设置文档的输出流
            response.setContentType("application/json;charset=utf-8");
            //获取文档输出流
            PrintWriter out = response.getWriter();
            //未登录
            Result result = new Result("500","sorry,请先登录!");
            //将java对象result转换成json字符串
            String resultJson = JSON.toJSONString(result);
            //将这个json字符串响应给客户端
            out.write(resultJson);
            out.close();
        }else{
            //如果token不为空,还不一定说明是登录的 - 无效的token(乱输入的)
            Claims claims = JWTUtils.checkJWT(token);
            //如果token是无效的/过期的,claim都是返回null
            if(null!=claims){
                //说明是有效的
                Integer userId = (Integer) claims.get("id");
                System.out.println("userId:"+userId);
                //放行
                //将userId放入到request作用域中
                request.setAttribute("userId",userId);
                return true;
            }else{
                //设置文档的输出流
                response.setContentType("application/json;charset=utf-8");
                //获取文档输出流
                PrintWriter out = response.getWriter();
                //可能是
                Result result = new Result("501","sorry,token已经过期了!");
                //将java对象result转换成json字符串
                String resultJson = JSON.toJSONString(result);
                //将这个json字符串响应给客户端
                out.write(resultJson);
                out.close();
            }
        }
        //return false;//true代表放行,false代表拦截
        return false;
    }
}
